/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

public class CryptoUtil {

    private static final Logger logger = LoggerFactory.getLogger(CryptoUtil.class);

    public static final String KEY_AES = "AES";

    private static final int DECRYPT_SIZE = 128;

    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * AES加密
     *
     * @param content  需要被加密的信息
     * @param password 加密需要的密码
     * @return 密文
     */
    public static String encrypt(Map content, String password) {
        try {
            if (null != content && !content.isEmpty()) {
                String info = new ObjectMapper().writeValueAsString(content);
                return doAES(info, password, 1);
            }
        } catch (Exception e) {
            logger.error("AES加密字符串异常", e.getMessage());
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content  AES加密过过的内容
     * @param password 加密时的密码
     * @return 明文
     */
    public static Map decrypt(String content, String password) {
        try {
            String info = doAES(content, password, 2);
            if (StringUtils.isNotEmpty(info)) {
                return new ObjectMapper().readValue(info, Map.class);
            }
        } catch (Exception e) {
            logger.error("AES解密字符串异常", e.getMessage());
        }
        return null;
    }


    /**
     * AES加密字符串
     *
     * @param content  需要被加密的字符串
     * @param password 加密需要的密码
     * @return 密文
     */
    public static String encryptByAES(String content, String password) {
        try {
            // 创建AES的Key生产者
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
            // 利用用户密码作为随机数初始化出
            kgen.init(DECRYPT_SIZE, new SecureRandom(password.getBytes()));
            // 128位的key生产者
            //加密没关系，SecureRandom是生成安全随机数序列，password.getBytes()是种子，只要种子相同，序列就一样，所以解密只要有password就行
            // 根据用户密码，生成一个密钥
            SecretKey secretKey = kgen.generateKey();
            // 返回基本编码格式的密钥，如果此密钥不支持编码，则返回null。
            byte[] enCodeFormat = secretKey.getEncoded();
            // 转换为AES专用密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_AES);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(KEY_AES);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            return parseByte2HexStr(result);
        } catch (Exception e) {
            logger.error("AES加密字符串异常", e.getMessage());
        }
        return null;
    }

    /**
     * 解密AES加密过的字符串
     *
     * @param content  AES加密过过的内容
     * @param password 加密时的密码
     * @return 明文
     */
    public static String decryptByAES(String content, String password) {
        try {
            // 创建AES的Key生产者
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
            kgen.init(DECRYPT_SIZE, new SecureRandom(password.getBytes()));
            // 根据用户密码，生成一个密钥
            SecretKey secretKey = kgen.generateKey();
            // 返回基本编码格式的密钥
            byte[] enCodeFormat = secretKey.getEncoded();
            // 转换为AES专用密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_AES);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(KEY_AES);
            // 初始化为解密模式的密码器
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(parseHexStr2Byte(content));
            // 明文
            return new String(result);
        } catch (Exception e) {
            logger.error("解密AES加密过的字符串异常", e.getMessage());
        }
        return null;
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 将16进制转换为二进制
     *
     * @param data
     * @return
     */
    public static byte[] parseHexStr2Byte(String data) {
        if (data.length() < 1) {
            return null;
        }
        byte[] result = new byte[data.length() / 2];
        for (int i = 0; i < data.length() / 2; i++) {
            int high = Integer.parseInt(data.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(data.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    /**
     * 加解密
     *
     * @param data 待处理数据
     * @param key  密钥
     * @param mode 加解密mode
     * @return
     */
    private static String doAES(String data, String key, int mode) throws Exception {
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            return null;
        }
        //判断是加密还是解密
        boolean encrypt = mode == Cipher.ENCRYPT_MODE;
        byte[] content;
        //true 加密内容 false 解密内容
        if (encrypt) {
            content = data.getBytes(DEFAULT_CHARSET);
        } else {
            content = parseHexStr2Byte(data);
        }
        //1.构造密钥生成器，指定为AES算法,不区分大小写
        KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
        //2.根据ecnodeRules规则初始化密钥生成器
        //生成一个128位的随机源,根据传入的字节数组
        //kgen.init(128, new SecureRandom(key.getBytes(DEFAULT_CHARSET)));
        // 上面 new SecureRandom()的方式在windows下没问题， 但在Linux环境下会导致解密失败
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes(DEFAULT_CHARSET));
        kgen.init(128, random);
        //3.产生原始对称密钥
        SecretKey secretKey = kgen.generateKey();
        //4.获得原始对称密钥的字节数组
        byte[] enCodeFormat = secretKey.getEncoded();
        //5.根据字节数组生成AES密钥
        SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, KEY_AES);
        //6.根据指定算法AES自成密码器
        // 创建密码器
        Cipher cipher = Cipher.getInstance(KEY_AES);
        //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
        // 初始化
        cipher.init(mode, keySpec);
        byte[] result = cipher.doFinal(content);
        if (encrypt) {
            //将二进制转换成16进制
            return parseByte2HexStr(result);
        } else {
            return new String(result, DEFAULT_CHARSET);
        }
    }

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("wxUserId", "liaodafu");
        logger.info("明文："+map);
        String ticket = CryptoUtil.encrypt(map, "ticket");
        logger.info("加密：" + ticket);
        Map map1 = CryptoUtil.decrypt(ticket, "ticket");
        logger.info("解密："+map1);
        if (null !=map1 && map1.containsKey("wxUserId")){
            logger.info("用户"+map1.get("wxUserId"));
        }
    }
}
